package com.imooc.web.async;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * Created by zghgchao 2018/4/19 21:03
 * ContextRefreshedEvent:整个spring容器初始化完毕后的事件
 */
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferreResultHolder deferreResultHolder;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        /**
         * while:方法现在是放在公用的启动过程中，如果一直循环会阻塞其他进程，故将其放到一个线程中进行执行
         */
        new Thread(()->{
            while (true){
                // 如果监听到 completeOrder 字段有值，执行
                if (StringUtils.isNotBlank(mockQueue.getCompleOrder())){
                    String orderNumber = mockQueue.getCompleOrder();//从队列中获取订单号
                    logger.info("返回订单处理结果："+orderNumber);
                    deferreResultHolder.getMap().get(orderNumber).setResult("place order success");//调用setResult时说明整个异步调用已完成，开始往回返回了
                    mockQueue.setCompleOrder(null);//将completeOrder设置为空，否则一直循环了
                }else {//没有监听到则睡100毫秒
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


    }
}
